package com.gw.udf;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.hadoop.hive.ql.exec.UDF;
//import org.apache.log4j.Logger;

import com.gw.util.Constants;
import com.gw.util.geoip2.GWDatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Subdivision;

public class IP2Region extends UDF {

//	private static Logger log = Logger.getLogger(IP2Region.class);
	
	private static GWDatabaseReader reader = null;

	static {
		String path = IP2Region.class.getResource("/").getFile().toString();
		try {
//			System.out.println(path + Constants.geoIPFile);
			File database = new File(path + Constants.geoIPFile);
			reader = new GWDatabaseReader.Builder(database).build();
			
		} catch (IOException e) {
//			log.error(e.getMessage());
		}
		
	}

	@SuppressWarnings("finally")
	public static String evaluate(String ip,int i) {
		InetAddress ipAddress;
		String region = null;
		try {
			ipAddress = InetAddress.getByName(ip);
			CityResponse response = null;
			response = reader.city(ipAddress);
			Country country = response.getCountry();
			Subdivision subdivision = response.getMostSpecificSubdivision();
			City city = response.getCity();
			if(country!=null && i==0){
				region = country.getNames().get("zh-CN") != null ? country.getNames().get("zh-CN") : country.getNames().get("en") ;
			}
			else if(subdivision!=null && i == 1 ){
				
				region = Constants.provinceCN.get(subdivision.getIsoCode()) != null ? 
						Constants.provinceCN.get(subdivision.getIsoCode()) :
							subdivision.getNames().get("en")	;
			}
			else if(city!=null && i == 2){
				String province = city.getNames().get("zh-CN");
				if(province != null && province.lastIndexOf("市") > 0){ 
					province = province.substring(0,province.length()-1);
				}
				region =  province != null ? province : city.getNames().get("en");
			} 
			
//			Postal postal = response.getPostal();
			//获取经纬度，暂时不需要
//			Location location = response.getLocation();
//			System.out.println(location.getLatitude());  // 44.9733
//			System.out.println(location.getLongitude()); // -93.2323
		
		} catch (Exception e) {
//			log.error(e.getMessage());
		} finally{
			return region;
		}
		
	}

	public static void main(String[] args) throws UnknownHostException,
			IOException, GeoIp2Exception {
		String ip = "223.104.6.25";
		System.out.println(evaluate(ip,0) + ":" + evaluate(ip,1) + ":" + evaluate(ip,2));

	}

}
